﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.Utils.Win;
using DevExpress.XtraBars.Docking2010.Views.WindowsUI;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Popup;
using EduFormManager.Models;
using EduFormManager.Models.Repo;
using EduFormManager.Properties;
using ItemCheckEventArgs = DevExpress.XtraEditors.Controls.ItemCheckEventArgs;

namespace EduFormManager.Forms.UserControls
{
    public partial class XtraDictionaryEduPassportControl : XtraBaseControl, ISupportDocumentActions
    {
        private EduOrg m_edu;
        private bool m_isManualSelect;
        public XtraDictionaryEduPassportControl(WindowsUIView view)
            : base(view)
        {
            InitializeComponent();
            InitializeProps();
        }

        private void InitializeProps()
        {
            municipalityBindingSource.DataSourceChanged += municipalityBindingSource_DataSourceChanged;
            eduOrgStatusBindingSource.DataSourceChanged += eduOrgStatusBindingSource_DataSourceChanged;
            eduOrgTypeBindingSource.DataSourceChanged += eduOrgTypeBindingSource_DataSourceChanged;
            eduOrgKindBindingSource.DataSourceChanged += eduOrgKindBindingSource_DataSourceChanged;
            ownershipTypeBindingSource.DataSourceChanged += ownershipTypeBindingSource_DataSourceChanged;

            //this.comboBoxMunit.Click += (sender, args) =>
            //{
            //    this.comboBoxMunit.Enabled = true;
            //};
        }

        void ownershipTypeBindingSource_DataSourceChanged(object sender, EventArgs e)
        {
            this.comboBoxOwnershipType.Properties.Items.Clear();
            this.comboBoxOwnershipType.Properties.Items.AddRange(ownershipTypeBindingSource.List);
        }

        void eduOrgKindBindingSource_DataSourceChanged(object sender, EventArgs e)
        {
            this.comboBoxEduKind.Properties.Items.Clear();
            this.comboBoxEduKind.Properties.Items.AddRange(eduOrgKindBindingSource.List);
        }

        void eduOrgTypeBindingSource_DataSourceChanged(object sender, EventArgs e)
        {
            this.comboBoxEduType.Properties.Items.Clear();
            this.comboBoxEduType.Properties.Items.AddRange(eduOrgTypeBindingSource.List);
        }

        void eduOrgStatusBindingSource_DataSourceChanged(object sender, EventArgs e)
        {
            this.comboBoxEduStatus.Properties.Items.Clear();
            this.comboBoxEduStatus.Properties.Items.AddRange(eduOrgStatusBindingSource.List);
        }

        void municipalityBindingSource_DataSourceChanged(object sender, EventArgs e)
        {
            this.comboBoxMunit.Properties.Items.Clear();
            this.comboBoxMunit.Properties.Items.AddRange(municipalityBindingSource.List);
        }

        public IList<EduOrgStatus> DataSourceEduStatus
        {
            set
            {
                eduOrgStatusBindingSource.DataSource = value;
            }
        }

        public IList<OwnershipType> DataSourceOwnershipType
        {
            set
            {
                ownershipTypeBindingSource.DataSource = value;
            }
        }

        public IList<ActivityType> DataSourceActivityType
        {
            set
            {
                activityTypeBindingSource.DataSource = value;
            }
        }

        public IList<ManagementAgency> DataSourceManagementAgency
        {
            set
            {
                managementAgencyBindingSource.DataSource = value;
            }
        }

        public IList<ManagementAgencyActivity> DataSourceManagementAgencyActivity
        {
            set
            {
                managementAgencyActivityBindingSource.DataSource = value;
            }
        }

        public EduOrg Edu
        {
            get { return m_edu; }
            set
            {
                m_edu = value;
                this.FillData(m_edu);
            }
        }

        private void FillData(EduOrg edu)
        {
            if (edu == null)
            {
                throw new ArgumentNullException("edu", "EduOrg passed to pasport control is null");
            }
            this.comboBoxMunit.SelectedItem = edu.Municipality;

            m_isManualSelect = false;
            this.checkedComboBoxActivityType.SetEditValue(null);
            foreach (ActivityType at in edu.ActivityTypes) 
            {
                this.checkedComboBoxActivityType.Properties.Items[(object)at.Id].CheckState = CheckState.Checked;
            }
            this.checkedComboBoxManagementAgency.SetEditValue(null);
            foreach (ManagementAgency ma in edu.ManagementAgencies)
            {
                this.checkedComboBoxManagementAgency.Properties.Items[(object)ma.Id].CheckState = CheckState.Checked;
            }
            this.checkedComboBoxManagementAgencyActivity.SetEditValue(null);
            foreach (ManagementAgencyActivity maa in edu.ManagementAgencyActivities)
            {
                this.checkedComboBoxManagementAgencyActivity.Properties.Items[(object)maa.Id].CheckState = CheckState.Checked;
            }
            m_isManualSelect = true;

            this.comboBoxEduKind.SelectedItem = edu.Kind;
            this.comboBoxEduStatus.SelectedItem = edu.Status;
            this.comboBoxEduType.SelectedItem = edu.Type;
            this.comboBoxOwnershipType.SelectedItem = edu.OwnershipType;

            this.dateEditAccreditation.DateTime = edu.AccreditationDate;
            this.dateEditEndAccreditation.DateTime = edu.AccreditationEndDate;
            this.textBoxAccreditationFrom.Text = edu.AccreditationFrom;
            this.textBoxAccreditationNum.Text = edu.AccreditationNum;
            this.textBoxCode.Text = edu.Code;
            this.textBoxDirectorName.Text = edu.DirectorName;
            this.textBoxEduName.Text = edu.Name;
            this.textBoxEduShortname.Text = edu.ShortName;
            this.textBoxEmail.Text = edu.Email;

            this.dateEditLicense.DateTime = edu.LicenseDate;
            this.textBoxLicenseFrom.Text = edu.LicenseFrom;
            this.textBoxLicenseNum.Text = edu.LicenseNum;
            this.textBoxLink.Text = edu.Link;
            this.textBoxOKPOCode.Text = edu.OKPOCode;
            this.textBoxPhone.Text = edu.Phone;
            this.textBoxPost.Text = edu.PostAddress;

            this.checkBoxIsUngraded.Checked = edu.IsUngraded;
            this.checkBox1.Checked = edu.ManagementAgencyHasAuthority;

            this.numericUpDownBranchCount.Value = edu.BranchCount;

            this.textBoxOperator.Text = edu.Operator;
        }

        private void SaveData(EduOrg edu)
        {
            if (edu == null)
            {
                throw new ArgumentNullException("edu", "EduOrg passed to pasport control is null");
            }
            edu.Municipality = this.comboBoxMunit.SelectedItem as Municipality;
            edu.Kind = this.comboBoxEduKind.SelectedItem as EduOrgKind;
            edu.Status = this.comboBoxEduStatus.SelectedItem as EduOrgStatus;
            edu.Type = this.comboBoxEduType.SelectedItem as EduOrgType;
            edu.OwnershipType = this.comboBoxOwnershipType.SelectedItem as OwnershipType;

            edu.AccreditationDate = this.dateEditAccreditation.DateTime;
            edu.AccreditationEndDate = this.dateEditEndAccreditation.DateTime;
            edu.AccreditationFrom = this.textBoxAccreditationFrom.Text;
            edu.AccreditationNum = textBoxAccreditationNum.Text;
            edu.Code = this.textBoxCode.Text;
            edu.DirectorName = this.textBoxDirectorName.Text;
            edu.Name = this.textBoxEduName.Text;
            edu.ShortName = this.textBoxEduShortname.Text;
            edu.Email = this.textBoxEmail.Text;

            edu.LicenseDate = this.dateEditLicense.DateTime;
            edu.LicenseEndDate = DateTime.Now;
            edu.LicenseFrom = this.textBoxLicenseFrom.Text;
            edu.LicenseNum = textBoxLicenseNum.Text;
            edu.Link = this.textBoxLink.Text;
            edu.OKPOCode = this.textBoxOKPOCode.Text;
            edu.Phone = this.textBoxPhone.Text;
            edu.PostAddress = this.textBoxPost.Text;

            edu.IsUngraded = this.checkBoxIsUngraded.Checked;
            edu.ManagementAgencyHasAuthority = this.checkBox1.Checked;

            edu.BranchCount = decimal.ToInt32(this.numericUpDownBranchCount.Value);
            string operatorName = this.textBoxOperator.Text.Trim();
            if (!string.IsNullOrEmpty(operatorName))
                edu.Operator = operatorName;
        }

        public void Save()
        {
            Save(null);
        }
        protected override void Save(Document doc)
        {
            if (this.CanSave(doc))
            {
                try
                {
                    this.SaveData(m_edu);
                    RepoHelper.Repo.Save(m_edu);
                    this.ShowFlyoutMessageBox("Информация", "Сохранено.", FlyoutCommand.OK);
                }
                catch (Exception ex)
                {
                    this.ShowFlyoutMessageBox("Ошибка", ex.ToString(), FlyoutCommand.OK);
                }
            }
            else
            {
                this.ShowFlyoutMessageBox("Ошибка", "Проверьте правильно ли все заполнено: поля название, кр. название, тип, статус, вид, муниципалитет", FlyoutCommand.OK);
            }
            
        }
        public bool CanSave()
        {
            return CanSave(null);
        }
        protected override bool CanSave(Document doc)
        {
            return !String.IsNullOrEmpty(this.textBoxEduName.Text) && !String.IsNullOrEmpty(this.textBoxEduShortname.Text)
                && comboBoxEduKind.SelectedItem != null && comboBoxEduStatus.SelectedItem != null && comboBoxEduType.SelectedItem != null
                && comboBoxMunit.SelectedItem != null && comboBoxOwnershipType.SelectedItem != null;
        }

        private void checkedComboBoxManagementAgency_Popup(object sender, EventArgs e)
        {
            PopupContainerForm form = (sender as IPopupControl).PopupWindow as PopupContainerForm;
            CheckedListBoxControl cl = form.Controls[3].Controls[0] as CheckedListBoxControl;
            cl.ItemCheck += checkedComboBoxManagementAgency_ItemCheck;
        }

        private void checkedComboBoxManagementAgency_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (m_isManualSelect && e.State != CheckState.Indeterminate)
            {
                int maId = (int)this.checkedComboBoxManagementAgency.Properties.Items[e.Index].Value;
                ManagementAgency ma = (this.managementAgencyBindingSource.List as List<ManagementAgency>).Find(x => x.Id == maId);
                
                if (e.State == CheckState.Checked)
                {
                    if (!m_edu.ManagementAgencies.Contains(ma))
                        m_edu.ManagementAgencies.Add(ma);
                }
                else
                {
                    if (m_edu.ManagementAgencies.Contains(ma))
                        m_edu.ManagementAgencies.Remove(ma);
                }
            }
        }

        private void checkedComboBoxManagementAgencyActivity_Popup(object sender, EventArgs e)
        {
            PopupContainerForm form = (sender as IPopupControl).PopupWindow as PopupContainerForm;
            CheckedListBoxControl cl = form.Controls[3].Controls[0] as CheckedListBoxControl;
            cl.ItemCheck -= checkedComboBoxManagementAgencyActivity_ItemCheck;
            cl.ItemCheck += checkedComboBoxManagementAgencyActivity_ItemCheck;
        }

        private void checkedComboBoxManagementAgencyActivity_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (m_isManualSelect)
            {
                int maaId = (int)this.checkedComboBoxManagementAgencyActivity.Properties.Items[e.Index].Value;
                ManagementAgencyActivity maa = (this.managementAgencyActivityBindingSource.List as List<ManagementAgencyActivity>).Find(x => x.Id == maaId);
                if (e.State == CheckState.Checked)
                {
                    if (!m_edu.ManagementAgencyActivities.Contains(maa))
                        m_edu.ManagementAgencyActivities.Add(maa);
                }
                else
                {
                    if (m_edu.ManagementAgencyActivities.Contains(maa))
                        m_edu.ManagementAgencyActivities.Remove(maa);
                }
            }
        }

        private void checkedComboBoxActivityType_Popup(object sender, EventArgs e)
        {
            PopupContainerForm form = (sender as IPopupControl).PopupWindow as PopupContainerForm;
            CheckedListBoxControl cl = form.Controls[3].Controls[0] as CheckedListBoxControl;
            cl.ItemCheck += checkedComboBoxActivityType_ItemCheck;
        }

        private void checkedComboBoxActivityType_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (m_isManualSelect)
            {
                int atId = (int)this.checkedComboBoxActivityType.Properties.Items[e.Index].Value;
                ActivityType at = (this.activityTypeBindingSource.List as List<ActivityType>).Find(x => x.Id == atId);
                if (e.State == CheckState.Checked)
                {
                    if (!m_edu.ActivityTypes.Contains(at))
                        m_edu.ActivityTypes.Add(at);
                }
                else
                {
                    if (m_edu.ActivityTypes.Contains(at))
                        m_edu.ActivityTypes.Remove(at);
                }
            }
        }

        public void OnQueryDocumentActions(IDocumentActionsArgs args)
        {
            args.DocumentActions.Add(new DocumentAction(Save) { Caption = "Сохранить", Image = Resources.glyphicons_206_ok_2 });
        }
    }
}
